<template>
  <div class="hello">
    <el-button style="float:left;" size="small" type="primary" @click="handleChooseData">{{title}}</el-button>
		<el-dialog title="客户选择" :visible.sync = "deviceZoneData.dialogTableVisible" width="80%">
      <el-button style="float:left;" size="small" type="primary" @click="handleClearData">清空所有</el-button>
      <el-button style="float:left;" size="small" type="primary" @click="handleAddData">添加选中的</el-button>
        <el-table :data="deviceZoneData.device_datas" ref="table" @selection-change="handleSelectionChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="id" label="客户名称"></el-table-column>
        <el-table-column prop="case_info_name" label="手机号"></el-table-column>
        <el-table-column prop="zone_code" label="身份证号"></el-table-column>
        <el-table-column prop="zone_sn" label="客户身份"></el-table-column>
      </el-table>
      <el-pagination :page-size="deviceZoneData.pageSize" @current-change="currentChange"
                              :current-page="deviceZoneData.currentPage"
                              :page-sizes="deviceZoneData.pageSizes"
                              :total="deviceZoneData.total"
                              layout="total, sizes, prev, pager, next"
                              @size-change='sizeChange'>
      </el-pagination>
		</el-dialog>
  </div>
</template>

<script>
export default {
  name: "ChooseDialogTalbe",
	props: ["title", "checkedData"],
  data() {
    return {
      deviceZoneData:{
        dialogTableVisible: false,
        multipleSelectionAll: [], // 所有选中的数据包含跨页数据
        multipleSelection: [], // 当前页选中的数据
        device_datas: [], // 表格数据
        idKey:'id', //标识列表数据中每一行的唯一键的名称(需要按自己的数据改一下)
        keywords:'',//搜索关键字
        is_online:'',//是否在线
        search_type:'3',//选择是否挂载
        zoneTypeList:[],//区域类型子类型列表
        zoneType:"",//区域类型

        total: 0, //总条数
        pageSize: 10, //每页显示条数
        pageSizes: [10, 20, 50],
        currentPage: 1,
      },
    };
  },
  methods: {
			handleChooseData () {				
					this.deviceZoneData.currentPage = 1;
					this.queryData();
					this.deviceZoneData.dialogTableVisible = true;
			},
			handleClearData () {				
				this.deviceZoneData.multipleSelectionAll = []
				this.$emit('handleChooseData', [])
				this.deviceZoneData.dialogTableVisible = false
			},
			handleAddData () {				
				this.changePageCoreRecordData();
        if (this.deviceZoneData.multipleSelectionAll.length <= 0) {           
            this.$message({  message: '无勾选数据！', type: 'warning' });
            return;
				}
				this.$emit('handleChooseData', this.deviceZoneData.multipleSelectionAll);
				this.deviceZoneData.dialogTableVisible = false;
			},
    // 设置选中的方法
    setSelectRow() {
      if (!this.deviceZoneData.multipleSelectionAll || this.deviceZoneData.multipleSelectionAll.length <= 0) {
        return;
      }
      // 标识当前行的唯一键的名称
      let idKey = this.deviceZoneData.idKey;
      let selectAllIds = [];
      let that = this;
      this.deviceZoneData.multipleSelectionAll.forEach(row => {
        selectAllIds.push(row[idKey]);
      });
      this.$refs.table.clearSelection();
      for (var i = 0; i < this.deviceZoneData.device_datas.length; i++) {
        if (selectAllIds.indexOf(this.deviceZoneData.device_datas[i][idKey]) >= 0) {
          // 设置选中，记住table组件需要使用ref="table"
          this.$refs.table.toggleRowSelection(this.deviceZoneData.device_datas[i], true);
        }
      }
    },
    // 记忆选择核心方法
    changePageCoreRecordData() {
      // 标识当前行的唯一键的名称
      let idKey = this.deviceZoneData.idKey;
      let that = this;
      // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
      if (this.deviceZoneData.multipleSelectionAll.length <= 0) {
        this.deviceZoneData.multipleSelectionAll = this.deviceZoneData.multipleSelection;
        return;
      }
      // 总选择里面的key集合
      let selectAllIds = [];
      this.deviceZoneData.multipleSelectionAll.forEach(row => {
        selectAllIds.push(row[idKey]);
      });
      let selectIds = [];
      // 获取当前页选中的id
      this.deviceZoneData.multipleSelection.forEach(row => {
        selectIds.push(row[idKey]);
        // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
        if (selectAllIds.indexOf(row[idKey]) < 0) {
          that.deviceZoneData.multipleSelectionAll.push(row);
        }
      });
      let noSelectIds = [];
      // 得到当前页没有选中的id
      this.deviceZoneData.device_datas.forEach(row => {
        if (selectIds.indexOf(row[idKey]) < 0) {
          noSelectIds.push(row[idKey]);
        }
      });
      noSelectIds.forEach(id => {
        if (selectAllIds.indexOf(id) >= 0) {
          for (let i = 0; i < that.deviceZoneData.multipleSelectionAll.length; i++) {
            if (that.deviceZoneData.multipleSelectionAll[i][idKey] == id) {
              // 如果总选择中有未被选中的，那么就删除这条
              that.deviceZoneData.multipleSelectionAll.splice(i, 1);
              break;
            }
          }
        }
      });
    },
    currentChange(val) {
      // 改变页的时候调用一次
      this.changePageCoreRecordData();
      this.deviceZoneData.currentPage = val;
      this.queryData();
    },
    sizeChange(val) {
      // 改变每页显示条数的时候调用一次
      this.changePageCoreRecordData();
      this.deviceZoneData.pageSize = val;
      this.queryData();
    },
    handleSelectionChange(val) {
      // console.log(val)
      // table组事件,记件选中得加上@selection-change="handleSelectionChange"
      this.deviceZoneData.multipleSelection = val;
    },
    queryData() {
      let url = '/sys/device_zone/search_zone?search_type='+ this.deviceZoneData.search_type + '&zone_type='+ this.deviceZoneData.zoneType +
        '&page=' + this.deviceZoneData.currentPage + '&page_size=' + this.deviceZoneData.pageSize + '&keywords=' + encodeURIComponent(this.deviceZoneData.keywords) +
        '&is_online=' + this.deviceZoneData.is_online + '&org_type=1&org_id_list='+ "047cd4bc88b04112ba61ee484a77aba1"
      this.$api.get(url)
      .then(data=>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return;
        }
        if(data){
          let _data = data.data;
          // this.deviceZoneData.dialogTableVisible = true;
          this.deviceZoneData.device_datas= _data.dataList;
          this.deviceZoneData.total = _data.dataCount;
          this.deviceZoneData.currentPage = _data.pageCode;
          this.deviceZoneData.pageSize = _data.pageSize;
          // console.log(this.deviceZoneData.device_datas);
          
        }else{
          this.deviceZoneData.device_datas = [];
        }
        setTimeout(() => {
            this.setSelectRow();
        }, 200);
        this.$Bus.$emit('Loading',false);
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false);
      })
      // start-----模拟动态分页
      
      // this.tableData = []
      // this.pagination.totalRows = 100;



      // let i = (this.pagination.pageNumber - 1) * this.pagination.pageSize + 1
      // let max = this.pagination.pageNumber * this.pagination.pageSize
      // for (; i <= max; i ++) {
      //   this.tableData.push( { personId: i, personName: '小明同志'+i, telphone: '137000000'+i, idNo: i + '10212000000000011', linkType: '业主' })
      // }
      // end------模拟动态分页
      
    }, // 得到选中的所有数据
    getAllSelectionData() {
      // 再执行一次记忆勾选数据匹配，目的是为了在当前页操作勾选后直接获取选中数据
      this.changePageCoreRecordData();
      // console.log(this.deviceZoneData.multipleSelectionAll);
    }
},
 mounted: function() {
    this.$nextTick(function () {
          // 初始化渲染
          this.deviceZoneData.currentPage = 1
          this.queryData()
     })
  },
  watch: {
    'checkedData' : {
       handler(val) {
         // 转换一下目的是为了不被同步
        this.deviceZoneData.multipleSelectionAll = JSON.parse(JSON.stringify(val));
      },
      immediate: true,
      deep: true
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.el-pagination {
    background: none;
    text-align: right;
    margin-top: 10px;
}
</style>